const { userTaskDetail, userTaskCheckIn, getUserTaskCheckInPage } = require('../../../utils/task');
const { formatDateTime, formatDateTimeNoSeconds } = require('../../../utils/date');

let that;
Page({
  data: {
    task: {},
    checkedIn: false,
    countingDown: false,
    countDownSeconds: 0,
    showCheckInDialog: false,
    mediaType: '',
    mediaPath: '',
    fileBase64: '',
    remark: '',
    historyList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    allHistory: [], // 全部模拟数据
    endCountDown: '', // 新增：结束倒计时字符串
    endCountDownSeconds: 0, // 新增：结束倒计时秒数
    // 图片预览相关
    showImageViewer: false,
    previewImageUrl: '',
    imageScale: 1,
    lastDistance: 0,
    lastX: 0,
    lastY: 0,
    needRefresh: false,
    sliderLeft: 0,
    sliderMax: 0,
    sliderDragging: false,
    isLoading: true, // 新增：加载状态
    showMediaModal: false,
    previewMediaUrl: '',
    previewMediaType: '',
    isAudioPlaying: false,
    audioCurrentTime: 0,
    audioDuration: 1,
    isAudioSliderDragging: false,
    wasAudioPlayingBeforeDrag: false,
    isVideoPlaying: false
  },
  async onLoad(options) {
    try {
      that = this;
      wx.showLoading({ title: '加载中' });
      const detail = await userTaskDetail(options.id);
      
      // 格式化任务数据
      const task = {
        // 我的任务id
        id: options.id, 
        taskId: detail.taskId,
        imageUrl: detail.imageUrl || '/@assets/avatar.png',
        taskName: detail.taskName || '未命名任务',
        state: detail.state,
        statusClass: detail.state === 'running' ? 'doing' : 'ended',
        taskStartTimeFmt: formatDateTime(detail.taskStartTime),
        taskEndTimeFmt: formatDateTime(detail.taskEndTime),
        taskStartTime: detail.taskStartTime,
        taskEndTime: detail.taskEndTime,
        checkInStartTime: detail.checkInStartTime || '00:00:00',
        checkInEndTime: detail.checkInEndTime || '23:59:59',
        joinTime: formatDateTimeNoSeconds(detail.joinTime),
        cycleRule: detail.cycleRule || '每天',
        checkInCountDownSeconds: detail.checkInCountDownSeconds || 0,
        checkInMustMedia: detail.checkInMustMedia,
        checkInRealTimeMedia: detail.checkInRealTimeMedia,
        overCheckInFlag: detail.overCheckInFlag || 'no',
        completionRate: detail.completionRate || '0%',
        continuousDays: detail.continuousDays || 0,
        totalCheckIns: detail.totalCheckIns || 0,
        validCheckIns: detail.validCheckIns || 0,
        earliestCheckIn: detail.earliestCheckIn || '',
        latestCheckIn: detail.latestCheckIn || ''
      };

      this.setData({ 
        task, 
        checkedIn: detail.checkedIn,
        isLoading: false // 设置加载完成
      });

      // 加载第一页历史记录
      await this.loadHistoryList();

      // 计算结束倒计时
      this.initEndCountDown(task.taskEndTime);
      wx.hideLoading();
    } catch (e) {
      console.error('加载任务详情失败:', e);
      wx.hideLoading();
      wx.showToast({ 
        title: e.data.msg || '加载任务详情失败', 
        icon: 'none',
        duration: 1500,
        complete: () => {
          // 延迟返回，让用户看到错误提示
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }
  },
  onReachBottom() {
    // 分页加载下一页
    if (!this.data.hasMore) return;
    const { page, pageSize, allHistory, historyList } = this.data;
    const nextPage = page + 1;
    const start = (nextPage - 1) * pageSize;
    const nextList = allHistory.slice(start, start + pageSize);
    const newList = historyList.concat(nextList);
    this.setData({
      historyList: newList,
      page: nextPage,
      hasMore: newList.length < allHistory.length
    });
  },

  navigateToTaskDetail () {
    wx.navigateTo({
      url: '/pages/task/task-detail/task-detail?id=' + this.data.task.taskId
      // 如果需要传递任务ID或其他参数，可以像上面这样拼接
    });
  },
  onCheckIn() {
  // 如果超出打卡时间，直接返回
    if (this.data.task.overCheckInFlag === 'yes') {
      wx.showToast({ 
        title: '已超出打卡时间', 
        icon: 'none' 
      });
      return;
    }
    
    if (this.data.task.checkInCountDownSeconds) {
      this.setData({ countingDown: true, countDownSeconds: this.data.task.checkInCountDownSeconds });
      this.startCountDown();
    } else {
      this.setData({ showCheckInDialog: true });
    }
  },
  startCountDown() {
    if (this.data.countDownSeconds <= 0) {
      this.setData({ countingDown: false, showCheckInDialog: true });
      return;
    }
    this.countdownTimer = setTimeout(() => {
      this.setData({ countDownSeconds: this.data.countDownSeconds - 1 });
      this.startCountDown();
    }, 1000);
  },
  onChooseMedia() {
    let sourceType = ['album', 'camera'];
    // 实时打卡，只能拍照
    if (this.data.task.checkInRealTimeMedia === 'yes') {
      sourceType = ['camera'];
    }
    const fs = wx.getFileSystemManager();

    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video', 'audio'],
      sourceType: sourceType,
      success: (res) => {
        const file = res.tempFiles[0];
        
        // 检查文件大小，4MB = 2 * 1024 * 1024 = 2097152 bytes
        const maxSize = 4 * 1024 * 1024; // 2MB
        if (file.size > maxSize) {
          wx.showToast({ 
            title: '文件大小不能超过4MB', 
            icon: 'none',
            duration: 2000
          });
          return;
        }
        
        // 判断是否为音频（兼容 fileType 不为 audio 的情况）
        const isAudio = (file.fileType === 'audio') || (file.tempFilePath && /\.mp3$/i.test(file.tempFilePath));
        fs.readFile({
          filePath: file.tempFilePath, // 第一个文件的路径
          encoding: 'base64',
          success(res) {
            if (isAudio) {
              that.setData({
                mediaType: 'audio',
                mediaPath: file.tempFilePath,
                fileBase64: res.data
              });
            } else {
              that.setData({
                mediaType: file.fileType,
                mediaPath: file.tempFilePath,
                fileBase64: res.data
              });
            }
          },
          fail(err) {
            console.error("读取文件失败:", err);
            wx.showToast({ 
              title: '读取文件失败', 
              icon: 'none' 
            });
          }
        });
      },
      fail: (err) => {
        console.error('选择文件失败:', err);
        wx.showToast({ 
          title: '选择文件失败', 
          icon: 'none' 
        });
      }
    });
  },
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value });
  },
  /**
   * 提交打卡
   */
  async onSubmitCheckIn() {
    // 必须上传媒体信息，但是媒体信息是空的
    if (this.data.task.checkInMustMedia === 'yes' && !this.data.fileBase64) {
      wx.showToast({ title: '请上传图片或视频', icon: 'none' });
      return;
    }

    try {
      // 构建打卡参数
      const param = {
        userTaskId: this.data.task.id,
        checkInDesc: this.data.remark,
        mediaType: this.data.mediaType,
        mediaPath: this.data.mediaPath,
        fileBase64: this.data.fileBase64
      };

      // 调用打卡接口
      await userTaskCheckIn(param.userTaskId, param);
      
      wx.showToast({ title: '打卡成功', icon: 'success' });
      
      // 获取上一页实例并刷新
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        console.log('上一页路由:', prevPage.route);
        
        // 根据页面路由执行对应的刷新逻辑
        if (prevPage.route.includes('my-task')) {
          // my-task页面
          if (typeof prevPage.loadTasks === 'function') {
            console.log('调用my-task页面的loadTasks方法');
            prevPage.loadTasks(true);
          }
        } else if (prevPage.route.includes('task-detail')) {
          // task-detail页面
          if (typeof prevPage.loadTaskDetail === 'function') {
            prevPage.loadTaskDetail();
          } else if (typeof prevPage.onLoad === 'function') {
            const options = prevPage.options || {};
            prevPage.onLoad(options);
          }
        } else {
          // 其他页面，尝试通用刷新方法
          if (typeof prevPage.refresh === 'function') {
            prevPage.refresh();
          } else if (typeof prevPage.loadData === 'function') {
            prevPage.loadData();
          } else if (typeof prevPage.loadTaskList === 'function') {
            prevPage.loadTaskList();
          } else if (typeof prevPage.loadHistoryList === 'function') {
            prevPage.loadHistoryList();
          } else if (typeof prevPage.onLoad === 'function') {
            const options = prevPage.options || {};
            prevPage.onLoad(options);
          }
        }
        
        // 强制更新上一页数据
        prevPage.setData({
          needRefresh: true
        });
      }
      
      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        wx.navigateBack({
          success: () => {
            // 返回成功后，再次尝试刷新上一页
            const currentPages = getCurrentPages();
            const currentPage = currentPages[currentPages.length - 1];
            if (currentPage && currentPage.data.needRefresh) {
              // 移除刷新标记
              currentPage.setData({
                needRefresh: false
              });
              
              // 根据页面类型执行不同的刷新逻辑
              if (currentPage.route.includes('my-task')) {
                // 我的任务页面
                if (typeof currentPage.loadTasks === 'function') {
                  console.log('返回后调用my-task页面的loadTasks方法');
                  currentPage.loadTasks(true);
                } else if (typeof currentPage.onShow === 'function') {
                  currentPage.onShow();
                }
              } else if (currentPage.route.includes('task-detail')) {
                // 任务详情页面
                if (typeof currentPage.loadTaskDetail === 'function') {
                  currentPage.loadTaskDetail();
                } else if (typeof currentPage.onShow === 'function') {
                  currentPage.onShow();
                }
              } else {
                // 其他页面，尝试通用刷新方法
                if (typeof currentPage.onShow === 'function') {
                  currentPage.onShow();
                }
              }
            }
          }
        });
      }, 800);
    } catch (e) {
      console.error('打卡失败:', e);
      wx.showToast({ 
        title: e.data.msg || '打卡失败', 
        icon: 'none' 
      });
    }
  },
  onUnload() {
    if (this.endCountDownTimer) clearTimeout(this.endCountDownTimer);
    if (this.countdownTimer) clearTimeout(this.countdownTimer);
  },
  // 新增：初始化结束倒计时
  initEndCountDown(endTimeStr) {
    const endTime = new Date(endTimeStr).getTime();
    const now = Date.now();
    let left = Math.floor((endTime - now) / 1000);
    this.setData({ endCountDownSeconds: left > 0 ? left : 0 });
    this.updateEndCountDown();
  },
  // 新增：更新结束倒计时显示
  updateEndCountDown() {
    let left = this.data.endCountDownSeconds;
    if (left <= 0) {
      this.setData({ endCountDown: '已结束' });
      return;
    }
    const d = Math.floor(left / 86400);
    const h = Math.floor((left % 86400) / 3600);
    const m = Math.floor((left % 3600) / 60);
    const s = left % 60;
    let str = '';
    if (d > 0) str += d + '天';
    if (h > 0 || d > 0) str += h.toString().padStart(2, '0') + '时';
    str += m.toString().padStart(2, '0') + '分';
    str += s.toString().padStart(2, '0') + '秒';
    this.setData({ endCountDown: str, endCountDownSeconds: left - 1 });
    this.endCountDownTimer = setTimeout(() => this.updateEndCountDown(), 1000);
  },
  // 图片预览相关方法
  onPreviewImage(e) {
    const url = e.currentTarget.dataset.url;
    this.setData({
      showImageViewer: true,
      previewImageUrl: url
    });
  },

  onImageViewerClose() {
    this.setData({
      showImageViewer: false,
      previewImageUrl: ''
    });
  },

  stopPropagation() {
    // 阻止事件冒泡
  },

  onImageTouchStart(e) {
    if (e.touches.length === 2) {
      // 双指缩放
      const xMove = e.touches[1].clientX - e.touches[0].clientX;
      const yMove = e.touches[1].clientY - e.touches[0].clientY;
      const distance = Math.sqrt(xMove * xMove + yMove * yMove);
      this.setData({ lastDistance: distance });
    } else if (e.touches.length === 1) {
      // 单指移动
      this.setData({
        lastX: e.touches[0].clientX,
        lastY: e.touches[0].clientY
      });
    }
  },

  onImageTouchMove(e) {
    if (e.touches.length === 2) {
      // 双指缩放
      const xMove = e.touches[1].clientX - e.touches[0].clientX;
      const yMove = e.touches[1].clientY - e.touches[0].clientY;
      const distance = Math.sqrt(xMove * xMove + yMove * yMove);
      const scale = this.data.imageScale * (distance / this.data.lastDistance);
      
      // 限制缩放范围
      if (scale >= 0.5 && scale <= 3) {
        this.setData({
          imageScale: scale,
          lastDistance: distance
        });
      }
    } else if (e.touches.length === 1) {
      // 单指移动
      const deltaX = e.touches[0].clientX - this.data.lastX;
      const deltaY = e.touches[0].clientY - this.data.lastY;
      
      this.setData({
        lastX: e.touches[0].clientX,
        lastY: e.touches[0].clientY
      });
    }
  },

  onImageTouchEnd() {
    // 触摸结束，可以在这里添加回弹动画等效果
  },

  // 加载历史记录列表
  async loadHistoryList() {
    try {
      const { page, pageSize, task } = this.data;
      const res = await getUserTaskCheckInPage(task.id, page, pageSize);
      
      // 格式化历史记录数据
      const formattedList = res.records.map(item => ({
        id: item.id,
        time: formatDateTimeNoSeconds(item.checkInTime),
        remark: item.checkInDesc || '',
        mediaType: item.mediaType,
        mediaPath: item.mediaPath,
        state: item.state,
        stateText: this.getStateText(item.state)
      }));

      this.setData({
        historyList: page === 1 ? formattedList : [...this.data.historyList, ...formattedList],
        hasMore: res.records.length === pageSize
      });
    } catch (e) {
      console.error('加载历史记录失败:', e);
      wx.showToast({ title: '加载历史记录失败', icon: 'none' });
    }
  },

  // 获取状态文本
  getStateText(state) {
    const stateMap = {
      'finish': '已完成',
      'overdue': '已过期',
      'quit': '已退出'
    };
    return stateMap[state] || '未知';
  },

  async onReachBottom() {
    if (!this.data.hasMore) return;
    this.setData({ page: this.data.page + 1 });
    await this.loadHistoryList();
  },

  onShow() {
    // 页面显示时，检查是否需要刷新数据
    if (this.data.needRefresh) {
      this.setData({ needRefresh: false });
      // 重新加载任务详情和历史记录
      this.loadTaskDetail();
      this.loadHistoryList();
    }
  },

  // 重新加载任务详情
  async loadTaskDetail() {
    try {
      const detail = await userTaskDetail(this.data.task.id);
      
      // 格式化任务数据
      const task = {
        // 我的任务id
        id: this.data.task.id, 
        imageUrl: detail.imageUrl || '/@assets/avatar.png',
        taskName: detail.taskName || '未命名任务',
        state: detail.state,
        statusClass: detail.state === 'running' ? 'doing' : 'ended',
        taskStartTimeFmt: formatDateTime(detail.taskStartTime),
        taskEndTimeFmt: formatDateTime(detail.taskEndTime),
        taskStartTime: detail.taskStartTime,
        taskEndTime: detail.taskEndTime,
        checkInStartTime: detail.checkInStartTime || '00:00:00',
        checkInEndTime: detail.checkInEndTime || '23:59:59',
        joinTime: formatDateTimeNoSeconds(detail.joinTime),
        cycleRule: detail.cycleRule || '每天',
        checkInCountDownSeconds: detail.checkInCountDownSeconds || 0,
        checkInMustMedia: detail.checkInMustMedia,
        checkInRealTimeMedia: detail.checkInRealTimeMedia,
        overCheckInFlag: detail.overCheckInFlag || 'no',
        completionRate: detail.completionRate || '0%',
        continuousDays: detail.continuousDays || 0,
        totalCheckIns: detail.totalCheckIns || 0,
        validCheckIns: detail.validCheckIns || 0,
        earliestCheckIn: detail.earliestCheckIn || '',
        latestCheckIn: detail.latestCheckIn || ''
      };

      this.setData({ 
        task, 
        checkedIn: detail.checkedIn
      });

      // 重新计算结束倒计时
      this.initEndCountDown(task.taskEndTime);
    } catch (e) {
      console.error('重新加载任务详情失败:', e);
    }
  },
  onReady() {
    // 计算滑块最大可滑动距离
    const query = wx.createSelectorQuery().in(this);
    query.select('.check-in-slider-bar').boundingClientRect();
    query.select('.check-in-slider-btn').boundingClientRect();
    query.exec(res => {
      if (res && res[0] && res[1]) {
        const max = res[0].width - res[1].width;
        this.setData({ sliderMax: max, sliderLeft: 0 });
      }
    });
  },
  onSliderStart(e) {
    if (this.data.task.overCheckInFlag === 'yes' || this.data.isLoading) return;
    // 阻止默认行为
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
    
    this.data.sliderDragging = true;
    this.data.startX = e.touches[0].clientX;
    this.data.startLeft = this.data.sliderLeft;
  },
  onSliderMove(e) {
    if (!this.data.sliderDragging || this.data.task.overCheckInFlag === 'yes' || this.data.isLoading) return;
    
    // 阻止默认行为，防止页面滑动
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
    
    const moveX = e.touches[0].clientX - this.data.startX;
    let left = this.data.startLeft + moveX;
    if (left < 0) left = 0;
    if (left > this.data.sliderMax) left = this.data.sliderMax;
    this.setData({ sliderLeft: left });
  },
  onSliderEnd(e) {
    if (this.data.task.overCheckInFlag === 'yes' || this.data.isLoading) return;
    
    // 阻止默认行为
    e.preventDefault && e.preventDefault();
    e.stopPropagation && e.stopPropagation();
    
    this.data.sliderDragging = false;
    if (this.data.sliderLeft >= this.data.sliderMax - 10) {
      this.setData({ sliderLeft: this.data.sliderMax });
      this.onCheckIn();
    } else {
      this.setData({ sliderLeft: 0 });
    }
  },

  // 处理滑动区域的触摸事件，防止页面滑动
  onSliderBarTouchMove(e) {
    // 如果正在拖动滑块，阻止页面滑动
    if (this.data.sliderDragging) {
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
    }
  },

  onGoToTaskSetting() {
    // 跳转到我的任务设置页面，传递当前任务id
    wx.navigateTo({
      url: `/pages/task/my-task-setting/my-task-setting?userTaskId=${this.data.task.id}`
    });
  },

  previewMedia(e) {
    const { url, type } = e.currentTarget.dataset;
    if (type === 'image') {
      const images = this.data.historyList
        .filter(item => item.mediaType === 'image' && item.mediaPath)
        .map(item => item.mediaPath);
      wx.previewImage({
        current: url,
        urls: images.length ? images : [url]
      });
    } else if (type === 'video') {
      this.setData({
        showMediaModal: true,
        previewMediaUrl: url,
        previewMediaType: type
      });
    } else if (type === 'audio') {
      if (this.innerAudio) {
        this.innerAudio.destroy();
        this.innerAudio = null;
      }
      this.innerAudio = wx.createInnerAudioContext();
      this.innerAudio.src = url;
      this.innerAudio.autoplay = false;
      this.innerAudio.obeyMuteSwitch = false;
      this.innerAudio.onCanplay(() => {
        setTimeout(() => {
          this.setData({
            audioDuration: this.innerAudio.duration || 1
          });
        }, 200);
      });
      this.innerAudio.onTimeUpdate(() => {
        if (!this.data.isAudioSliderDragging) {
          this.setData({
            audioCurrentTime: this.innerAudio.currentTime
          });
        }
      });
      this.innerAudio.onEnded(() => {
        this.setData({ isAudioPlaying: false, audioCurrentTime: 0 });
      });
      this.setData({
        showMediaModal: true,
        previewMediaUrl: url,
        previewMediaType: type,
        isAudioPlaying: false,
        audioCurrentTime: 0,
        audioDuration: 1,
        isAudioSliderDragging: false,
        wasAudioPlayingBeforeDrag: false
      });
    }
  },
  toggleAudioPlay() {
    if (!this.innerAudio) return;
    if (this.data.isAudioPlaying) {
      this.innerAudio.pause();
      this.setData({ isAudioPlaying: false });
    } else {
      this.innerAudio.play();
      this.setData({ isAudioPlaying: true });
    }
  },
  onAudioLoadedMetaData(e) {
    let duration = Number(e.detail.duration) || 1;
    if (duration < 1) duration = 1;
    this.setData({ audioDuration: duration });
  },
  onAudioTimeUpdate(e) {
    if (!this.data.isAudioSliderDragging) {
      this.setData({ audioCurrentTime: Number(e.detail.currentTime) });
    }
  },
  onAudioSliderChange(e) {
    const value = Number(e.detail.value);
    if (this.innerAudio) {
      this.innerAudio.seek(value);
      if (this.data.isAudioPlaying) {
        this.innerAudio.play();
      }
    }
    this.setData({
      audioCurrentTime: value,
      isAudioSliderDragging: false
    });
  },
  onAudioSliderChanging(e) {
    this.setData({
      isAudioSliderDragging: true,
      audioCurrentTime: Number(e.detail.value)
    });
  },
  closeMediaModal() {
    if (this.innerAudio) {
      this.innerAudio.stop();
      this.innerAudio.destroy();
      this.innerAudio = null;
    }
    this.setData({
      showMediaModal: false,
      previewMediaUrl: '',
      previewMediaType: '',
      isVideoPlaying: false
    });
  },
  playPreviewVideo() {
    this.setData({ isVideoPlaying: true }, () => {
      const videoCtx = wx.createVideoContext('previewVideo', this);
      videoCtx.play();
    });
  },
  onVideoPlay() {
    this.setData({ isVideoPlaying: true });
  },
  onVideoPause() {
    this.setData({ isVideoPlaying: false });
  },
  stopPropagation() {},
}); 